/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.requirement.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.dto.ActivityQueryCriteria;
import com.fzhucc.modules.requirement.domain.Requirement;
import com.fzhucc.modules.requirement.domain.dto.RequirementDto;
import com.fzhucc.modules.requirement.domain.dto.RequirementMsgSciQueryCriteria;
import com.fzhucc.modules.requirement.domain.dto.RequirementQueryCriteria;
import com.fzhucc.modules.requirement.repository.RequirementRepository;
import com.fzhucc.modules.requirement.service.mapstruct.RequirementMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.thinktank.domain.Academician;
import com.fzhucc.modules.thinktank.domain.Capital;
import com.fzhucc.modules.thinktank.domain.Company;
import com.fzhucc.modules.thinktank.domain.Leader;
import com.fzhucc.modules.thinktank.domain.dto.AcademicianDto;
import com.fzhucc.modules.thinktank.domain.dto.CapitalDto;
import com.fzhucc.modules.thinktank.domain.dto.CompanyDto;
import com.fzhucc.modules.thinktank.domain.dto.LeaderDto;
import com.fzhucc.modules.thinktank.repository.AcademicianRepository;
import com.fzhucc.modules.thinktank.repository.CapitalRepository;
import com.fzhucc.modules.thinktank.repository.CompanyRepository;
import com.fzhucc.modules.thinktank.repository.LeaderRepository;
import com.fzhucc.modules.thinktank.service.mapstruct.AcademicianMapper;
import com.fzhucc.modules.thinktank.service.mapstruct.CapitalMapper;
import com.fzhucc.modules.thinktank.service.mapstruct.CompanyMapper;
import com.fzhucc.modules.thinktank.service.mapstruct.LeaderMapper;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.fzhucc.modules.thinktank.domain.Academician.THINKTANK_TYPE_ACADEMICIAN;
import static com.fzhucc.modules.thinktank.domain.Capital.THINKTANK_TYPE_CAPITAL;
import static com.fzhucc.modules.thinktank.domain.Company.THINKTANK_TYPE_COMPANY;
import static com.fzhucc.modules.thinktank.domain.Leader.THINKTANK_TYPE_LEADER;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-02-28
 **/
@Service
@RequiredArgsConstructor
public class RequirementService {

    private final LeaderRepository leaderRepository;

    private final AcademicianRepository academicianRepository;

    private final CompanyRepository companyRepository;

    private final CapitalRepository capitalRepository;
    private final RequirementRepository requirementRepository;
    private final RequirementMapper requirementMapper;

    private final LeaderMapper leaderMapper;

    private final CompanyMapper companyMapper;

    private final CapitalMapper capitalMapper;

    private final AcademicianMapper academicianMapper;

    public static final String other = "其他";

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    public Map<String, Object> queryAll(RequirementQueryCriteria criteria, Pageable pageable) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<Requirement> page = requirementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<RequirementDto> map = page.map(requirementMapper::toDto);
        List<RequirementDto> list = map.getContent();
        if (list != null) {
            for (RequirementDto requirementDto : list) {
                String thinktankType = requirementDto.getThinktankType();//智库类型
                if (thinktankType.equals(THINKTANK_TYPE_ACADEMICIAN)){//院士之家
                    Optional<Academician> res = academicianRepository.findById(requirementDto.getThinktankId());
                    if (res.isPresent()) {
                        Academician academician = res.get();
                        AcademicianDto academicianDto = academicianMapper.toDto(academician);
                        requirementDto.setThinktank(academicianDto);
                    }
                }else if(thinktankType.equals(THINKTANK_TYPE_CAPITAL)){//产业资本
                    Optional<Capital> res = capitalRepository.findById(requirementDto.getThinktankId());
                    if (res.isPresent()) {
                        Capital capital = res.get();
                        CapitalDto capitalDto = capitalMapper.toDto(capital);
                        requirementDto.setThinktank(capitalDto);
                    }
                }else if(thinktankType.equals(THINKTANK_TYPE_COMPANY)){//上市公司
                    Optional<Company> res = companyRepository.findById(requirementDto.getThinktankId());
                    if (res.isPresent()) {
                        Company company = res.get();
                        CompanyDto companyDto = companyMapper.toDto(company);
                        requirementDto.setThinktank(companyDto);
                    }
                }else if(thinktankType.equals(THINKTANK_TYPE_LEADER)){//产业龙头
                    Optional<Leader> res = leaderRepository.findById(requirementDto.getThinktankId());
                    if (res.isPresent()) {
                        Leader leader = res.get();
                        LeaderDto leaderDto = leaderMapper.toDto(leader);
                        requirementDto.setThinktank(leaderDto);
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(RequirementQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null  && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public List<RequirementDto> queryAll(RequirementQueryCriteria criteria) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return requirementMapper.toDto(requirementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public RequirementDto findById(Integer id) {
        Requirement requirement = requirementRepository.findById(id).orElseGet(Requirement::new);
        ValidationUtil.isNull(requirement.getId(), "Requirement", "id", id);
        return requirementMapper.toDto(requirement);
    }

    @Transactional(rollbackFor = Exception.class)
    public RequirementDto create(Requirement resources) {
        String orgArea = "";
        String thinktankType = resources.getThinktankType();//智库类型
        if (thinktankType.equals(THINKTANK_TYPE_ACADEMICIAN)){//院士之家
            Optional<Academician> res = academicianRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("院士之家未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_CAPITAL)){//产业资本
            Optional<Capital> res = capitalRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("产业资本未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_COMPANY)){//上市公司
            Optional<Company> res = companyRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("上市公司未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_LEADER)){//产业龙头
            Optional<Leader> res = leaderRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("产业龙头未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else{
            throw new BadRequestException("未属于正确的智库类型,无法创建");
        }

        if (resources.getTechnicalField().equals(other)) {
            if (resources.getTechnicalFieldOther() == null || resources.getTechnicalFieldOther().equals("")) {
                throw new BadRequestException("所需技术领域为其他时需填写具体值");
            }
        }
        if (resources.getCooperation().equals(other)) {
            if (resources.getCooperationOther() == null || resources.getCooperationOther().equals("")) {
                throw new BadRequestException("所需合作方式为其他时需填写具体值");
            }
        }
        if (resources.getIsLongEstimate() == 0) {//不为长期
            if (resources.getEstimateTime() == null || resources.getEstimateEndTime() == null) {
                throw new BadRequestException("请输入技术需求时间段");
            }
        }
        if (resources.getIsLongEstimate() == 1) {//长期
            if (resources.getEstimateTime() != null || resources.getEstimateEndTime() != null) {
                throw new BadRequestException("技术需求时间为长期时则不需要输入技术需求时间段");
            }
        }
        resources.setOrgArea(orgArea);
        return requirementMapper.toDto(requirementRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Requirement resources) {
        String orgArea = "";
        String thinktankType = resources.getThinktankType();//智库类型
        if (thinktankType.equals(THINKTANK_TYPE_ACADEMICIAN)){//院士之家
            Optional<Academician> res = academicianRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("院士之家未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_CAPITAL)){//产业资本
            Optional<Capital> res = capitalRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("产业资本未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_COMPANY)){//上市公司
            Optional<Company> res = companyRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("上市公司未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else if(thinktankType.equals(THINKTANK_TYPE_LEADER)){//产业龙头
            Optional<Leader> res = leaderRepository.findById(resources.getThinktankId());
            if (!res.isPresent()) {
                throw new BadRequestException("产业龙头未找到");
            }else{
                orgArea = res.get().getOrgArea();
            }
        }else{
            throw new BadRequestException("未属于正确的智库类型,无法创建");
        }
        if (resources.getTechnicalField().equals(other)) {
            if (resources.getTechnicalFieldOther() == null || resources.getTechnicalFieldOther().equals("")) {
                throw new BadRequestException("所需技术领域为其他时需填写具体值");
            }
        }
        if (resources.getCooperation().equals(other)) {
            if (resources.getCooperationOther() == null || resources.getCooperationOther().equals("")) {
                throw new BadRequestException("所需合作方式为其他时需填写具体值");
            }
        }
        if (resources.getIsLongEstimate() == 0) {//不为长期
            if (resources.getEstimateTime() == null || resources.getEstimateEndTime() == null) {
                throw new BadRequestException("请输入技术需求时间段");
            }
        }
        if (resources.getIsLongEstimate() == 1) {//长期
            if (resources.getEstimateTime() != null || resources.getEstimateEndTime() != null) {
                throw new BadRequestException("技术需求时间为长期时则不需要输入技术需求时间段");
            }
        }
        Requirement requirement = requirementRepository.findById(resources.getId()).orElseGet(Requirement::new);
        ValidationUtil.isNull(requirement.getId(), "Requirement", "id", resources.getId());
        requirement.copy(resources);
        requirement.setOrgArea(orgArea);
        requirementRepository.save(requirement);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            requirementRepository.deleteById(id);
        }
    }

    public void download(List<RequirementDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RequirementDto requirement : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("智库id", requirement.getThinktankId());
            map.put("智库类型", requirement.getThinktankType());
            map.put("名称", requirement.getTitle());
            map.put("单位", requirement.getUnit());
            map.put("联系人姓名", requirement.getName());
            map.put("联系人职务", requirement.getPost());
            map.put("联系方式", requirement.getPhone());
            map.put("联系人邮箱", requirement.getEmail());
            map.put("所需技术领域  technical_field_type", requirement.getTechnicalField());
            map.put("所需技术领域其他  选择技术领域为其他时填写", requirement.getTechnicalFieldOther());
            map.put("所需技术成熟度   technology_maturity_type", requirement.getTechnologyMaturity());
            map.put("是否长期  技术需求有效时间   是长期  否填写时间段", requirement.getIsLongEstimate());
            map.put("技术需求开始时间    is_long_estimate为false才需填写", requirement.getEstimateTime());
            map.put("技术需求结束时间    is_long_estimate为false才需填写", requirement.getEstimateEndTime());
            map.put("拟采用的合作方式  cooperation_type", requirement.getCooperation());
            map.put("拟采用的研发金额  amount_type", requirement.getAmount());
            map.put("拟采用的合作方式其他   合作方式为其他时才需填写", requirement.getCooperationOther());
            map.put("描述", requirement.getDescribe());
            map.put("是否显示", requirement.getIsShow());
            map.put("排序", requirement.getSort());
            map.put("封面", requirement.getPic());
            map.put("区域划分", requirement.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}